package org.railage.server.util;

import java.util.Random;

/**
 * Class contains implode and passwordGen functions
 * 
 * @author Cyril Fertikov
 * 
 */
public class Utils {

	private Utils() {
	}

	/**
	 * Join array elements with a string
	 * 
	 * @param glue
	 *            Defaults to an empty string.
	 * @param pieces
	 *            The array of strings to implode.
	 * @return A string containing a string representation of all the array
	 *         elements in the same order, with the glue string between each
	 *         element.
	 */
	public static String implode(String glue, String[] pieces) {
		if (pieces == null) {
			return null;
		} else if (pieces.length == 0) {
			return "";
		} else {
			StringBuilder result = new StringBuilder();
			for (String piece : pieces) {
				result.append(piece).append(glue);
			}
			result.deleteCharAt(result.length() - 1);
			return result.toString();
		}
	}

	/**
	 * Password generation
	 * 
	 * @param length
	 *            Desired password length.
	 * @return Generated password.
	 */
	public static String passwordGen(int length) {
		String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		StringBuilder result = new StringBuilder();
		Random rand = new Random();
		for (int i = 0; i < length; i++) {
			int pos = rand.nextInt(chars.length());
			result.append(chars.charAt(pos));
		}
		return result.toString();
	}
}
